package com.meet.app.ui;

import android.annotation.SuppressLint;
import android.database.Cursor;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.view.View;
import android.widget.Toast;

import androidx.recyclerview.widget.DividerItemDecoration;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.meet.app.R;
import com.meet.app.adapter.AddFriendAdpater;
import com.meet.app.model.AddFriendModel;
import com.meet.framework.adapter.CommonAdapter;
import com.meet.framework.adapter.CommonViewHolder;
import com.meet.framework.base.BaseBackActivity;
import com.meet.framework.bmob.BmobManager;
import com.meet.framework.bmob.IMUser;
import com.meet.framework.java.SimulationData;
import com.meet.framework.utils.CommonUtils;
import com.meet.framework.utils.LogUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import cn.bmob.v3.exception.BmobException;
import cn.bmob.v3.listener.FindListener;

/**
 * 从通讯录导入
 */
public class ContactFirendActivity extends BaseBackActivity {

    private RecyclerView mContactView;

    private Map<String, String> mContactMap = new HashMap<>();


    private List<AddFriendModel> mList=new ArrayList<>();

    //标题
    public static final int TYPE_TITLE = 0;
    //内容
    public static final int TYPE_CONTENT = 1;

//    private AddFriendAdpater addFriendAdpater;
    private CommonAdapter<AddFriendModel> addFriendAdpater;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_contact_friend);
        initView();
    }

    private void initView() {
        mContactView = (RecyclerView) findViewById(R.id.mContactView);
        //列表的实现
        mContactView.setLayoutManager(new LinearLayoutManager(this));
        mContactView.addItemDecoration(new DividerItemDecoration(this, DividerItemDecoration.VERTICAL));
//        addFriendAdpater=new AddFriendAdpater(this, mList);
        addFriendAdpater=new CommonAdapter<>(mList, new CommonAdapter.OnMoreBindDataListener<AddFriendModel>() {
            @Override
            public int getItemType(int position) {
                return mList.get(position).getType();
            }

            @Override
            public void onBindViewHolder(AddFriendModel model, CommonViewHolder viewHolder, int type, int position) {
                //设置头像
                viewHolder.setImageUrl(ContactFirendActivity.this, R.id.iv_photo, model.getPhoto());
                //设置性别
                viewHolder.setImageResource(R.id.iv_sex,
                        model.isSex() ? R.drawable.img_boy_icon : R.drawable.img_girl_icon);
                //设置昵称
                viewHolder.setText(R.id.tv_nickname, model.getNickName());
                //年龄
                viewHolder.setText(R.id.tv_age, model.getAge() + getString(R.string.text_search_age));
                //设置描述
                viewHolder.setText(R.id.tv_desc, model.getDesc());

                if (model.isContact()) {
                    viewHolder.getView(R.id.ll_contact_info).setVisibility(View.VISIBLE);
                    viewHolder.setText(R.id.tv_contact_name, model.getContactName());
                    viewHolder.setText(R.id.tv_contact_phone, model.getContactPhone());
                }

                viewHolder.itemView.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        UserInfoActivity.startActivity(ContactFirendActivity.this,
                                model.getUserId());
//                        Toast.makeText(ContactFirendActivity.this, "position:"+position, Toast.LENGTH_SHORT).show();
                    }
                });
            }

            @Override
            public int getLayoutId(int type) {
                if (type == TYPE_TITLE) {
                    return R.layout.layout_search_title_item;
                } else if (type == TYPE_CONTENT) {
                    return R.layout.layout_search_user_item;
                }
                return 0;
            }
        });
        mContactView.setAdapter(addFriendAdpater);
//        addFriendAdpater.setOnClickListener(new AddFriendAdpater.OnclickListener() {
//            @Override
//            public void onClick(int position) {
//                Toast.makeText(ContactFirendActivity.this, "position:"+position, Toast.LENGTH_SHORT).show();
//            }
//        });

        loadContact();
        loadUser();
    }

//    private void loadUser(){
//        if(mContactMap.size()>0){
//            for(Map.Entry<String,String> entry:mContactMap.entrySet()){
//                BmobManager.getInstance().queryPhoneUser(entry.getValue(), new FindListener<IMUser>() {
//                    @Override
//                    public void done(List<IMUser> list, BmobException e) {
//                        if(e==null){
//                            if(!CommonUtils.isEmpty(list)){
//                                IMUser imUser=list.get(0);
//                                addContent(imUser,entry.getKey(),entry.getValue());
//                            }
//                        }
//                    }
//                });
//            }
//            addFriendAdpater.notifyDataSetChanged();
//        }
//    }

    private void loadUser(){
        if(mContactMap.size()>0) {
            int i=0;
            List<IMUser> userList=SimulationData.getUserList();
            for(Map.Entry<String,String> entry:mContactMap.entrySet()) {
                String name = entry.getKey();
                String value = entry.getValue();
                if(i>43){
                    continue;
                }
                IMUser imUser = userList.get(i);
                if (imUser != null) {
                    addContent(imUser, name, value);
                }
                i++;
            }
        }
    }



    /**
     * 加载联系人
     */
    @SuppressLint("Range")
    private void loadContact() {
        Cursor cursor = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI
                , null, null, null, null);
        String name;
        String phone;
        while (cursor.moveToNext()) {
            name = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
            phone = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
            LogUtils.i("name:" + name + " phone:" + phone);

            phone = phone.replace(" ", "").replace("-", "");
            mContactMap.put(name, phone);
        }
    }


    /**
     * 添加头部
     *
     * @param title
     */
    private void addTitle(String title) {
        AddFriendModel model = new AddFriendModel();
        model.setType(TYPE_TITLE);
        model.setTitle(title);
        mList.add(model);
        addFriendAdpater.notifyDataSetChanged();
    }

    /**
     * 添加内容
     *
     * @param imUser
     */
    private void addContent(IMUser imUser,String name,String phone) {
        AddFriendModel model = new AddFriendModel();
        model.setType(TYPE_CONTENT);
        model.setUserId(imUser.getObjectId());
        model.setPhoto(imUser.getPhoto());
        model.setSex(imUser.isSex());
        model.setAge(imUser.getAge());
        model.setNickName(imUser.getNickName());
        model.setDesc(imUser.getDesc());
        model.setContact(true);
        model.setContactName(name);
        model.setContactPhone(phone);
        mList.add(model);
        addFriendAdpater.notifyDataSetChanged();
    }

}
